package com.raos.example.Service;

import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

/**
 * 消息生产者
 *
 * @author raos
 * @date 2025-02-28
 */
@Component
public class RocketMQProducer {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    // 发送普通消息
    public void sendMessage(String topic, String message) {
        rocketMQTemplate.convertAndSend(topic, message);
        logger.info("发送普通消息：{}", message);
    }

    // 发送延时消息（单位：毫秒）
    public void sendDelayMessage(String topic, String message, long delayMillis) {
        // 默认值最长值 the delay time should not be bigger than the max delay 259200000ms;
        // 最大为延时毫秒数：259200000ms，即72小时
        /*rocketMQTemplate.syncSendDelayTimeMills(topic,
                MessageBuilder.withPayload(message).build(),
                delayMillis
        );*/
        long timeMillis = System.currentTimeMillis() + delayMillis;
        // 自定义延时毫秒数
        rocketMQTemplate.syncSendDeliverTimeMills(topic,
                MessageBuilder.withPayload(message).build(),
                timeMillis
        );
        logger.info("发送延时消息：{}，延时 {} ms", message, delayMillis);
    }

}
